<?php
namespace Common\Controller;
class WeixinbaseController extends AppframeController {
	/****借支申请表**/
	protected $borrow;
	/**员工基本信息表**/
	protected $wx_person;
	/**社招基本信息表**/
    protected $wx_invite;
    /**申请入职表**/
    protected $wx_apply_job;
    /***入职信息表**/
    protected $wx_income;
    protected $wx_money_exp;
    /***微信用户表非社招录入的用户*/
    protected $wx_user;
    protected $wx_model;
	public function _initialize() {
	    $this->wx_invite = D("Common/Invite");
	    $this->wx_apply_job = D("Common/ApplyJob");
	    $this->wx_income = D("Common/Income");
	    $this->wx_money_exp = D("Common/MoneyExp");
	    $this->wx_user = D("Common/WxUser");
	    $this->wx_model = D("Common/WxConfig");
	    $this->wx_person = D("Common/Person");
	    $this->borrow = D("Common/Borrow");
	     
		$this->set_action_success_error_tpl();
		parent::_initialize();
	}
	/****
	 * @info 社招用户信息
	 */
	public function getUserInfo(){
	    $uid = $_SESSION['uid'];
	    $data = $this->wx_invite->where(array("uid"=>$uid))->find();
	    $invite_count = $this->wx_apply_job->where(array("invite_id"=>$uid,"job_state" => 3))->count();
	    $user = $this->wx_user->where(array("uid"=>$uid))->field("nickname,headimgurl")->find();
	    $data['nickname'] = $user['nickname'];
	    $data['headimgurl'] = $user['headimgurl'];
	    $data['invite_count'] = $invite_count;
	    $data['total_money'] = $this->getTotalMoney($uid);
	    return $data;
	}

    /**
     * 如果没有进行过加盟并且加盟不通过那么跳转到加盟页面
     */
	public function check_is_invite(){
		if(APP_DEBUG){
			$_SESSION['uid'] = 15;
		}
        $uid = empty($_SESSION['uid'])? 0 : $_SESSION['uid'];
        $invite=$this->wx_invite->where([
            'uid'=>$uid,
            'state'=>2
        ])->find();
        if(empty($invite)){
            $this->redirect('Weixin/User/join');
        }
    }
    
    /**
     * @info 检查用户是否绑定了微信
     * @author Mojianguo
     * @date 2017年1月8日
     * @param $personID 检查当前用户则无需传值  员工ID，注不是社招人员ID
     * @return false  操作异常
     */
    public function check_is_person($personID){
    	if(empty($personID))
    	$personID = empty($_SESSION['personID'])? 0 : $_SESSION['personID'];
    	//if(empty($personID) || $personID<1) return false;
    	$person=$this->wx_person->where(['id'=>$personID])->find();
    	if(empty($person) || empty($person['open_id'])){/**没有绑定微信*/
    		$this->display("User/bindUserIndex");
    		exit();
    	}
    	return true;
    }
    
    /**
     * @info 检查用户是否有借支权限
     * @author Mojianguo
     * @date 2017年1月8日
     * @param $personID   员工ID，注不是社招人员ID
     * @return false  操作异常
     */
    public function check_is_borrow($personID = ''){
    	 $this->check_is_person($personID);
    	 /**判断用户是否在职**/
    	$result = $this->wx_apply_job->where(array("person_id"=>"$personID","job_state"=>3))->find();
    	if(empty($result) || count($result)<1)
    	return false;
    	return true;
    }
	/**
	 * 用户总金额
	 */
    public function getTotalMoney($uid){
	    $income_money = $this->wx_income->alias("a")
	       ->join("__APPLY_JOB__ as b ON b.id = a.apply_job_id")
	       ->where(array("b.invite_id"=>$uid))->sum("a.com_give");
	    
	    $where_exp['invite_id'] = $uid;
	    $where_exp['state'] = array('in','1,2');
	    $money_exp = $this->wx_money_exp
	       ->where($where_exp)->sum("money");
	    return $income_money-$money_exp;
	}
	/**
	 * 加载模板和页面输出 可以返回输出内容
	 * @access public
	 * @param string $templateFile 模板文件名
	 * @param string $charset 模板输出字符集
	 * @param string $contentType 输出类型
	 * @param string $content 模板输出内容
	 * @return mixed
	 */
	public function display($templateFile = '', $charset = '', $contentType = '', $content = '', $prefix = '') {
		parent::display($this->parseTemplate($templateFile), $charset, $contentType,$content,$prefix);
	}
	
	/**
	 * 获取输出页面内容
	 * 调用内置的模板引擎fetch方法，
	 * @access protected
	 * @param string $templateFile 指定要调用的模板文件
	 * 默认为空 由系统自动定位模板文件
	 * @param string $content 模板输出内容
	 * @param string $prefix 模板缓存前缀*
	 * @return string
	 */
	public function fetch($templateFile='',$content='',$prefix=''){
	    $templateFile = empty($content)?$this->parseTemplate($templateFile):'';
		return parent::fetch($templateFile,$content,$prefix);
	}
	
	/**
	 * 自动定位模板文件
	 * @access protected
	 * @param string $template 模板文件规则
	 * @return string
	 */
	public function parseTemplate($template='') {
		
		$tmpl_path=C("SP_TMPL_PATH");
		define("SP_TMPL_PATH", $tmpl_path);
		if($this->theme) { // 指定模板主题
		    $theme = $this->theme;
		}else{
		    // 获取当前主题名称
		    $theme      =    C('SP_DEFAULT_THEME');
		    if(C('TMPL_DETECT_THEME')) {// 自动侦测模板主题
		        $t = C('VAR_TEMPLATE');
		        if (isset($_GET[$t])){
		            $theme = $_GET[$t];
		        }elseif(cookie('think_template')){
		            $theme = cookie('think_template');
		        }
		        if(!file_exists($tmpl_path."/".$theme)){
		            $theme  =   C('SP_DEFAULT_THEME');
		        }
		        cookie('think_template',$theme,864000);
		    }
		}
		
		$theme_suffix="";
		
		if(C('MOBILE_TPL_ENABLED') && sp_is_mobile()){//开启手机模板支持
		    
		    if (C('LANG_SWITCH_ON',null,false)){
		        if(file_exists($tmpl_path."/".$theme."_mobile_".LANG_SET)){//优先级最高
		            $theme_suffix  =  "_mobile_".LANG_SET;
		        }elseif (file_exists($tmpl_path."/".$theme."_mobile")){
		            $theme_suffix  =  "_mobile";
		        }elseif (file_exists($tmpl_path."/".$theme."_".LANG_SET)){
		            $theme_suffix  =  "_".LANG_SET;
		        }
		    }else{
    		    if(file_exists($tmpl_path."/".$theme."_mobile")){
    		        $theme_suffix  =  "_mobile";
    		    }
		    }
		}else{
		    $lang_suffix="_".LANG_SET;
		    if (C('LANG_SWITCH_ON',null,false) && file_exists($tmpl_path."/".$theme.$lang_suffix)){
		        $theme_suffix = $lang_suffix;
		    }
		}
		
		$theme=$theme.$theme_suffix;
		
		C('SP_DEFAULT_THEME',$theme);
		
		$current_tmpl_path=$tmpl_path.$theme."/";
		// 获取当前主题的模版路径
		define('THEME_PATH', $current_tmpl_path);
		
		$cdn_settings=sp_get_option('cdn_settings');
		if(!empty($cdn_settings['cdn_static_root'])){
		    $cdn_static_root=rtrim($cdn_settings['cdn_static_root'],'/');
		    C("TMPL_PARSE_STRING.__TMPL__",$cdn_static_root."/".$current_tmpl_path);
		    C("TMPL_PARSE_STRING.__PUBLIC__",$cdn_static_root."/public");
		    C("TMPL_PARSE_STRING.__WEB_ROOT__",$cdn_static_root);
		}else{
		    C("TMPL_PARSE_STRING.__TMPL__",__ROOT__."/".$current_tmpl_path);
		}
		
		
		C('SP_VIEW_PATH',$tmpl_path);
		C('DEFAULT_THEME',$theme);
		
		define("SP_CURRENT_THEME", $theme);
		
		if(is_file($template)) {
			return $template;
		}
		$depr       =   C('TMPL_FILE_DEPR');
		$template   =   str_replace(':', $depr, $template);
		
		// 获取当前模块
		$module   =  MODULE_NAME;
		if(strpos($template,'@')){ // 跨模块调用模版文件
			list($module,$template)  =   explode('@',$template);
		}
		
		$module =$module."/";
		
		// 分析模板文件规则
		if('' == $template) {
			// 如果模板文件名为空 按照默认规则定位
			$template = CONTROLLER_NAME . $depr . ACTION_NAME;
		}elseif(false === strpos($template, '/')){
			$template = CONTROLLER_NAME . $depr . $template;
		}
		
		$file = sp_add_template_file_suffix($current_tmpl_path.$module.$template);
		$file= str_replace("//",'/',$file);
		if(!file_exists_case($file)) E(L('_TEMPLATE_NOT_EXIST_').':'.$file);
		return $file;
	}
	
	/**
	 * 设置错误，成功跳转界面
	 */
	private function set_action_success_error_tpl(){
		$theme      =    C('SP_DEFAULT_THEME');
		if(C('TMPL_DETECT_THEME')) {// 自动侦测模板主题
			if(cookie('think_template')){
				$theme = cookie('think_template');
			}
		}
		//by ayumi手机提示模板
		$tpl_path = '';
		if(C('MOBILE_TPL_ENABLED') && sp_is_mobile() && file_exists(C("SP_TMPL_PATH")."/".$theme."_mobile")){//开启手机模板支持
			$theme  =   $theme."_mobile";
			$tpl_path=C("SP_TMPL_PATH").$theme."/";
		}else{
			$tpl_path=C("SP_TMPL_PATH").$theme."/";
		}
		
		//by ayumi手机提示模板
		$defaultjump=THINK_PATH.'Tpl/dispatch_jump.tpl';
		$action_success = sp_add_template_file_suffix($tpl_path.C("SP_TMPL_ACTION_SUCCESS"));
		$action_error = sp_add_template_file_suffix($tpl_path.C("SP_TMPL_ACTION_ERROR"));
		if(file_exists_case($action_success)){
			C("TMPL_ACTION_SUCCESS",$action_success);
		}else{
			C("TMPL_ACTION_SUCCESS",$defaultjump);
		}

		if(file_exists_case($action_error)){
			C("TMPL_ACTION_ERROR",$action_error);
		}else{
			C("TMPL_ACTION_ERROR",$defaultjump);
		}
	}
	/****
	 * @info      根据入职时间查询用户借支限额
	 * @desc     在职0 -6天              0；
	 *                 企业发工资的当天额度清零，然后再从50/天开始累加
	 * @author  Mojianguo
	 * @date   2017年1月8
	 * @param string $personID  员工ID
	 * @return $result "comlist"在职公司列表；"maxVaule" 最大借支金额;
	 */
	public  function getBorrowNum($personID){
		if(empty($personID) ) return 0;
		$where['b.id'] = $personID;
		$where['a.job_state'] = 3; //在职企业列表
		$comList = $this->wx_apply_job->alias("a")
		->join("__PERSON__ as b ON b.id = a.person_id",'LEFT')
		->join("__COMS__ as c ON c.id = a.com_id",'LEFT')
		->where($where)->field("b.name,b.mobile,c.com_name,c.id as com_id,c.salaryday,a.injob_time")
		->select();
		$maxValue = 0;
		foreach ($comList as $key=>$com){
			$nowValue = $this->getMaxValue($com['injob_time'], $com['salaryday'],$personID,$com['com_id']);
			$comList[$key]['nowValue'] = $nowValue;   /**企业可借支金额*/
			if ($nowValue > $maxValue){
				$maxValue = $nowValue;
			}
		}////end for
		$result = array("comlist"=>$comList,"maxVaule"=>$maxValue);
		return $result;
	}
	
	/****
	 * @info      根据入职时间查询用户借支限额
	 * @desc     在职0 -6天              0；
	 *                 企业发工资的当天额度清零，然后再从50/天开始累加
	 * @author  Mojianguo
	 * @date   2017年1月8
	 * @param string $personID  员工ID
	 * @return $result "comlist"在职公司列表；"maxVaule" 最大借支金额;
	 */
	public  function getBorrowNumByComID($personID,$comID){
		if(empty($personID)  || empty($comID)) return 0;
		$where['person_id'] = $personID;
		$where['com_id'] = $comID;
		$where['job_state'] = 3; 
		$com = $this->wx_apply_job->alias("a")
		->join("__COMS__ as c ON c.id = a.com_id",'LEFT')
		->where($where)->field("c.salaryday,a.injob_time")
		->find();
		if(empty($com))return 0;
		return $this->getMaxValue($com['injob_time'], $com['salaryday'],$personID,$comID);
	}
	/***
	 * @info     获取最大借支金额
	 * @rule     1、在职天数大于7
	 *               2、1个月借支次数不能大于4次
	 *               3、额度在企业发薪日后清零
	 *               4、额度借了需要减掉
	 * @param long $injob_time  入职日期
	 * @param int $salaryDay   公司结算日
	 */
	private function getMaxValue(/**入职日期**/$injob_time,/**发薪日*/$salaryDay,/**用户ID*/$personID,/**公司ID*/$comID){
		if(empty($injob_time)||empty($salaryDay)) return 0; ///发工资日期为0表示该企业不能借支
		$ts = $this->borrow
                     ->where("personID='%s' and comID='%s' and MONTH(from_unixtime(requestdate))=MONTH(sysdate())",array($personID,$comID))
                     ->order("requestdate desc")
                     ->field("requestdate,last_requestdate")
                     -> select();  ////获取当月借支次数
		$sql =  $this->borrow->getLastSql();
		if(count($ts)>3)return 0; /***每月最大借支次数为4*/
	    $beforeBorrowDate = reset($ts)['last_requestdate'];  /***最近一次借支日期**/
		$ntime = time();/******当前日期*/
		$maxValue = 0;
		$Days=round(($ntime-$injob_time)/3600/24);/***总在职天数**/////公式： 当前时间 - 录入时间 = 计算间隔时间
		if($Days<7)  return 0;  //入职未满7天
		$nowDay = date('d');   /**当前几号**/
		if($salaryDay == -1){  //每月的最后一天发工资
			$salaryDay = date("t"); 
		}
		if($nowDay == $salaryDay) return 0;  //发工资当日清零
		$mDay = round(($ntime-$beforeBorrowDate)/3600/24);/**最近一次借支与当天的间隔天数**/
		$nDay = 0 ; 	/**清零后的日期**/
		if($nowDay > $salaryDay){
			$nDay = $nowDay - $salaryDay; 
			if ($Days <$nDay) $nDay = $Days;/**解决第一个月的问题**/
		}else{
			$beforeMaxDay = date('t', strtotime('-1 month'));  //上个月的天数
			$tDate = $beforeMaxDay - $salaryDay +  $nowDay;
			if($Days>$tDate || $Days==$tDate){  //在职天数是否大于$tDate
				$nDay = $tDate;
			}else{
				$nDay = $Days - 7;
			}
		}
		$tBool = true;
		if($nDay>$mDay){ /**之前借过钱*/
			$nDay = $mDay;
			$tBool = false;
		}
		if($nDay>0 && $tBool){
			return 200 + SUM_NUM * ($nDay-1);
		}else{
			return SUM_NUM * $nDay;
		}
	}
}